package initialize

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/olivere/elastic/v7"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"month_zg5/book_srv/common/global"
	"month_zg5/book_srv/logic"
	book_rpc "month_zg5/book_srv/proto"
	consule "month_zg5/book_srv/vender/consul"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func init() {
	InitViper()
	InitNacos()
	InitMysql()
	InitRedis()
	InitEs()
}
func InitViper() {
	path := "./etc/dev.yaml"
	viper.SetConfigFile(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.NacosConfig)
	log.Println(global.NacosConfig, "/")
}
func InitNacos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.NacosName, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}

	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   uint64(global.NacosConfig.Port),
		},
	}

	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})
	if err != nil {
		panic(err)
	}
	yaml.Unmarshal([]byte(content), &global.ServerConfig)
}
func InitGrpc() {
	GrpcServer := grpc.NewServer()
	Server := &logic.BookRpc{}
	book_rpc.RegisterBookServer(GrpcServer, Server)
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.ServerConfig.BookConf.Host, global.ServerConfig.BookConf.Port))
	if err != nil {
		panic(err)
	}
	go func() {
		if err = GrpcServer.Serve(listen); err != nil && err != http.ErrAbortHandler {
			panic(err)
		}
	}()
	consulClient := InitConsul()
	log.Println("书架项目服务端启动成功：：：")
	SigChan := make(chan os.Signal, 1)
	signal.Notify(SigChan, syscall.SIGTERM, syscall.SIGINT)
	<-SigChan
	err = consulClient.Deregister(global.ServerConfig.ConsulConf.Id)
	if err != nil {
		panic(err)
	}
	GrpcServer.Stop()
}
func InitConsul() consule.RegistryClient {
	var (
		err      error
		BaseHost string
		BasePort int
	)
	global.ConsulClient, err = api.NewClient(api.DefaultConfig())
	if err != nil {
		panic(err)
	}
	//过滤
	consulClient := consule.NewRegistryClient(global.ServerConfig.BookConf.Host, global.ServerConfig.BookConf.Port)
	i, err := consulClient.FilterByName(global.ServerConfig.ConsulConf.Name)
	for _, v := range i {
		BaseHost = v.Address
		BasePort = v.Port
		break
	}
	if BaseHost != "" && BasePort != 0 {
		log.Println("服务已经存在")
		return nil
	}
	//注册
	global.ServerConfig.ConsulConf.Id = uuid.NewString()
	err = consulClient.RegisterConsul(global.ServerConfig.ConsulConf.Id, global.ServerConfig.ConsulConf.Name, global.ServerConfig.ConsulConf.Tags)
	if err != nil {
		log.Println("注册失败")
		return nil
	}
	return consulClient
}
func InitMysql() {
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.ServerConfig.MysqlConf.Username, global.ServerConfig.MysqlConf.Password,
		global.ServerConfig.MysqlConf.Host, global.ServerConfig.MysqlConf.Port, global.ServerConfig.MysqlConf.Database,
	)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
			TablePrefix:   "book_",
		},
	})
	if err != nil {
		panic(err)
	}
	//连接池配置
	db, _ := global.DB.DB()
	db.SetMaxIdleConns(3)
	db.SetMaxIdleConns(3)
}
func InitRedis() {
	global.RedisClient = redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisConf.Host, global.ServerConfig.RedisConf.Port),
		DB:   global.ServerConfig.RedisConf.DB,
	})
}
func InitEs() {
	var err error
	dsn := fmt.Sprintf("http://%s:%d", global.ServerConfig.EsConf.Host, global.ServerConfig.EsConf.Port)
	global.EsClient, err = elastic.NewClient(elastic.SetURL(dsn), elastic.SetSniff(false))
	if err != nil {
		panic(err)
	}
}
